<?php

/**
 * Form input that uses select to display data
 *
 * @author shenlon
 */
class FormSelectInput extends FormInput {

    /**
     * Data used with input
     * @var type 
     */
    private $data;

    /**
     * Default constructor
     * @param string $name
     * @param string $required
     * @param Array $data
     * @param Array $options 
     */
    public function __construct($name, $required, $data, $options = array()) {
        parent::__construct($name, $required);
        $this->data = $data;
        if ($options != null)
            foreach ($options as $key => $value) {
                if (property_exists($this, $key))
                    $this->$key = $value;
                else
                    $this->optionalData[$key] = $value;
            }
    }

    /**
     * Renders form input by using select options to display data
     * @return String
     */
    public function renderFormInput() {
        $html = "<label for='{$this->name}'>{$this->label}</label>\n";
        $html .= "<select name='%s' ";
        if (count($this->optionalData) > 0) {
            foreach ($this->optionalData as $key => $value)
                $html .= "$key = '$value' ";
        }
        $html .= "%s>\n";
        foreach ($this->data as $key => $value) {
            $html .= "\t<option value='$value'>$value</option>\n";
        }
        $html .= "</select>\n<br/>";
        return sprintf($html, $this->name, $this->required);
    }

    /**
     * Validates data by calling FormInput->validateData and by checking if value exists in this input data array
     * @param object $data
     * @return Array
     */
    public function validateData($data) {
        $errorMsg = "Wartość $data nie istnieje w zbiorze wartości.";
        $errors = parent::validateData($data);
        if ($data != '') {
            if (!in_array($data, $this->data)) {
                if (!is_array($errors))
                    $errors = array($errorMsg);
                else
                    $errors[] = $errorMsg;
            }
        }
        return $errors;
    }

}

?>
